﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseCheckcarddetail;
using SHZY.BaseData.Entitys;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：检卡抽样方案明细.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Checkcarddetail", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseCheckcarddetailService : IQmsBaseCheckcarddetailService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseCheckcarddetailEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseCheckcarddetailService"/>类型的新实例.
    /// </summary>
    public QmsBaseCheckcarddetailService(
        ISqlSugarRepository<QmsBaseCheckcarddetailEntity> qmsBaseCheckcarddetailRepository,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseCheckcarddetailRepository;
        _userManager = userManager;
        _db = context.AsTenant();
    }

    /// <summary>
    /// 获取检卡抽样方案明细.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseCheckcarddetailInfoOutput>();
    }

    /// <summary>
    /// 获取检卡抽样方案列表.
    /// </summary>
    /// <param name="sampleId">抽样方案表id.</param>
    /// <returns></returns>
    [HttpGet("GetList/{sampleId}")]
    public async Task<dynamic> GetList(string sampleId)
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.SampleId == sampleId)
            .OrderBy(x => x.Sort).ToListAsync();
        return new { list = data.Adapt<List<QmsBaseCheckcarddetailInfoOutput>>() };

    }

    /// <summary>
    /// 新建检卡抽样方案明细.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseCheckcarddetailCrInput input)
    {
        if (await _repository.AnyAsync(x => x.SampleId == input.sampleId && x.InnspectionName == input.innspectionName && x.InnspectionEntry == input.innspectionEntry && x.DeleteMark == null))
            throw Oops.Oh("检验项目与条目不能重复维护");

        var entity = input.Adapt<QmsBaseCheckcarddetailEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新检卡抽样方案明细.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseCheckcarddetailUpInput input)
    {
        if (await _repository.AnyAsync(x => x.SampleId == input.sampleId && x.InnspectionName == input.innspectionName && x.InnspectionEntry == input.innspectionEntry && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh("检验项目与条目不能重复维护");
        var entity = input.Adapt<QmsBaseCheckcarddetailEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);

    }

    /// <summary>
    /// 删除检卡抽样方案明细.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<QmsBaseCheckcarddetailEntity>().SetColumns(it => new QmsBaseCheckcarddetailEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }
}